import React, {Component} from 'react'
import {Modal, Button,message,Table,Input,Checkbox,Icon,InputNumber,Popconfirm } from 'antd'
import {WeaDialog,WeaRightMenu,WeaTop,WeaInput } from 'ecCom';

import ColorPanel from '../colorPanel'

class SetTagModal extends Component {
    constructor(props) {
        super(props)
        this.state = {
            visible: false,
            isShowPanel:false,
            tagValue:"",
            bgcolor:"",
            color:"",
            index:0,
            isrefresh:1,
            dataSource: props.data || []
        }
        this.columns = [{
                title: '标签名称',
                dataIndex: 'title',
                width: '30%',
                render:(text,record,index)=>{
                    return <WeaInput  value={`${record.title}`} onBlur={value => this.onTitleChange(value,index)} />
            }
            }, {
                title: '标签颜色',
                dataIndex: 'labelColor',
                render: (text, record, index) => {
                    return  <div>
                        <span style={{background:`${record.labelColor}`,color:`${record.textColor}`,padding:"2px 3px"}}>
                            {record.title}
                        </span>
                        <Icon type="edit"  style={{marginLeft:"5px"}} onClick={()=>this.showColorPanel(record.title,record.labelColor,record.textColor,index)}/>
                    </div>
                },
            }, {
                title: 'TAB显示',
                dataIndex: 'isUsed',
                render: (text, record, index) => {
                    return  <Checkbox defaultChecked={Number(`${record.isUsed}`)} onChange={()=>this.setTabShow(index)}/>
                },
            }, {
                title: '顺序',
                dataIndex: 'labelOrder',
                render: (text, record, index) => {
                    return <InputNumber min={0} max={99999} defaultValue={`${record.labelOrder}`} onChange={(value )=>this.setOrder(value,index)}/>
                },
                width:"10%"
            },{
                title: '操作',
                dataIndex: 'operation',
                render: (text, record, index) => {
                    return (
                    this.state.dataSource.length >0 ?
                    (
                        <Popconfirm title="是否确认删除?" onConfirm={() =>this.onDelete(index)}>
                            <a>删除</a>
                        </Popconfirm>
                    ) : null
                    );
                },
        }];
    }
    set visible(value) {
        this.setState({visible: value})
    }

     componentDidMount() {
		const { dataSource = [] } = this.state;
		this.setState({dataSource: this.addKeytoDatas(dataSource)})
    }
    componentWillReceiveProps(nextProps,nextState) {
		const {  data = [] } = this.props;
		const _datas = nextProps.data || [];
		JSON.stringify(data) !== JSON.stringify(_datas) && this.setState({dataSource: this.addKeytoDatas(_datas)});
	}
    addKeytoDatas(datas){
		let _datas = datas.map((data, i) => {
			let _data = {...data};
			_data.key = i
			return _data
		})
		return _datas
	}
    onDelete = (index) => {
        const {actions,type} = this.props;
        const {dataSource} = this.state;
        let _dataSource = [].concat(dataSource);

        if(Number(_dataSource[index].id)){
           actions.crmTagDelete({id:dataSource[index].id,type:type});
        }
        _dataSource.splice(index, 1);
        this.setState({ dataSource:_dataSource });
    }
    onAdd = () => {
        const {  dataSource } = this.state;
        const len = dataSource.length;
        const order = (function(){
            if(len){
                let orderMax = Number(dataSource[0].labelOrder);
                for(let i=1;i<len;i++){
                    if(Number(dataSource[i].labelOrder) > orderMax){
                        orderMax = Number(dataSource[i].labelOrder);
                    }
                }
                return orderMax
            }else{
                return -1
            }
        })();
        const newData = {  
            key: len+1,
            title: '',
            isUsed: "0",
            labelOrder:  order+1,
            labelColor:"#8CC76D",
            "textColor": "#ffffff",
        };
        this.setState({dataSource: [...dataSource, newData]});
    }
    onTitleChange=(value,index)=>{
        const {dataSource,isrefresh} = this.state;
        let _dataSource =  [].concat(dataSource);
        const isHas = (function(){ 
            for(let i=0; i<_dataSource.length; i++){
                if(_dataSource[i].title == value && i != index){
                    Modal.warning({
                        title: '系统提示',
                        content: '标签名称已存在!',
                    });
                    return false
                }
            }
            return true
        })();
        if(isHas){_dataSource[index].title = value; }
        this.setState({dataSource:_dataSource,isShowPanel:false,isrefresh:isrefresh+1});
    }
    setTabShow=(index)=>{
        const {dataSource,} = this.state;
        let _dataSource =  [].concat(dataSource);
        _dataSource[index].isUsed = Number(_dataSource[index].isUsed) ? "0":"1";
        this.setState({dataSource:_dataSource});
    }
    setOrder=(val,index)=>{
        const {dataSource,} = this.state;
        let _dataSource =  [].concat(dataSource);
        _dataSource[index].labelOrder = val;
        this.setState({dataSource:_dataSource});
    }
    render() {
        let {visible,dataSource,isShowPanel,tagValue,bgcolor,color,isrefresh} = this.state;
        const {data} = this.props;
        const columns = this.columns;
        return (
            <WeaDialog
                style={{width: 700,height:400}}
                visible={visible}
                title={'标签设置'}
                icon="icon-coms-crm"
                iconBgcolor="#6d3cf7"
                buttons={[
                    <Button onClick={() => this.setVisible(false)}>关闭</Button>
                ]}
                onCancel={() => this.setVisible(false)}
            >
                <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                    <WeaTop
                        title={"标签设置"}
                        loading={true}
                        icon={<i className='icon-portal-workflow' />}
                        iconBgcolor='#55D2D4'
                        buttons={this.getButtons()}
                        buttonSpace={10}
                        showDropIcon={true}
                        dropMenuDatas={this.getRightMenu()}
                        onDropMenuClick={this.onRightMenuClick.bind(this)}
                    >
                        {isShowPanel && <ColorPanel data ={tagValue} bgcolor={bgcolor} valuecolor={color} sureColor={this.sureColor} cancelColor={this.cancelColor} />}
                        <Table 
                            key={isrefresh}
                            columns={columns} 
                            dataSource={dataSource}
                            pagination={false}
                           />
                    </WeaTop>
                </WeaRightMenu>
                
            </WeaDialog>
        )
    }

    setVisible = (visible) => {
        this.setState({visible: visible})
    }

    getButtons() {
         const {actions} = this.props;
        let btnArr = [];
        btnArr.push(<Button type="primary"  onClick={this.doSave} >保存</Button>)
        btnArr.push(<Button type="primary"  onClick={this.onAdd.bind(this)} >新建</Button>)
        return btnArr
    }
     onRightMenuClick(key){
    	 const {actions,} = this.props;
    	if(key == '0'){
            this.doSave();
    	}
    	if(key == '1'){
    	}
    	if(key == '2'){
    	}
    }
    getRightMenu(){
    	// const {comsWeaTable,sharearg,actions} = this.props;
    	let btns = [];
    	btns.push({
    		icon: <i className='icon-coms-Preservation'/>,
    		content:'保存'
    	});
        btns.push({
    		icon: <i className='icon-coms-Collection2'/>,
    		content:'收藏'
    	});
        btns.push({
            icon: <i className='icon-coms-help'/>,
            content:'帮助',
        });
    	return btns
    }

    showColorPanel=(value,bgcolor,color,index)=>{
        this.setState({isShowPanel:true,tagValue:value,bgcolor:bgcolor,color:color,index:index})
    }
    sureColor=(bg,valcolor)=>{
        const {bgcolor,color,index,dataSource} = this.state;
        let _dataSource =  [].concat(dataSource);
        _dataSource[index].labelColor = bg;
        _dataSource[index].textColor= valcolor;
        this.setState({dataSource:_dataSource,isShowPanel:false});
        // console.log(bg,color)
    }

    cancelColor=()=>{
        this.setState({isShowPanel:false})
    }

    doSave=()=>{
        const {actions,type} = this.props;
        const {dataSource}  = this.state;
        actions.crmTagEdit({tagsInfo:JSON.stringify(dataSource),type:type});
        this.setState({visible:false,isShowPanel:false})
    }
}

export default SetTagModal